package io.github.xxyopen.novel.core.filter;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.github.xxyopen.novel.core.config.XssProperties;
import io.github.xxyopen.novel.core.wrapper.XssHttpServletRequestWrapper;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 防止 XSS 攻击的过滤器
 *
 * @author xiongxiaoyang
 * @date 2022/5/17
 */
/*
一、什么是XSS攻击？
XSS（Cross-Site Scripting，跨站脚本攻击） 是常见的安全漏洞，攻击者通过向网页注入恶意脚本（如JavaScript），
当其他用户浏览该页面时，脚本会在其浏览器中执行。例如：
<!-- 假设用户输入被直接显示 -->
用户评论：<script>alert('你的Cookie是：'+document.cookie)</script>
如果未过滤，其他用户看到此评论时会弹出自己的Cookie，攻击者可窃取用户会话。
 */
@Component //声明为Spring管理的Bean
@ConditionalOnProperty(value = "novel.xss.enabled", havingValue = "true")//仅当配置文件（如application.yml）中novel.xss.enabled=true时生效。
@WebFilter(urlPatterns = "/*", filterName = "xssFilter")//定义过滤器的URL匹配规则（/*匹配所有请求）。
@EnableConfigurationProperties(value = {XssProperties.class})//启用对XssProperties类的配置绑定。
@RequiredArgsConstructor//Lombok自动生成构造函数，注入final修饰的XssProperties。
public class XssFilter implements Filter {

    private final XssProperties xssProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        if (handleExcludeUrl(req)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
            (HttpServletRequest) servletRequest);
        filterChain.doFilter(xssRequest, servletResponse);
    }

    private boolean handleExcludeUrl(HttpServletRequest request) {
        if (CollectionUtils.isEmpty(xssProperties.excludes())) {
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : xssProperties.excludes()) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}